import React, { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import type { Word, GameSettings, Category, GameStats, CategoryStats, Pet, Achievement, UserProgress } from '@/types/vocabulary';
import { defaultCategories } from '@/types/vocabulary';
import { loadVocabulary, saveVocabulary, loadSettings, saveSettings, loadGameStats, saveGameStats, loadCategoryStats, saveCategoryStats, loadPets, savePets, loadAchievements, saveAchievements, loadUserProgress, saveUserProgress } from '@/utils/localStorage';

interface VocabularyContextType {
  vocabulary: Word[];
  settings: GameSettings;
  gameStats: GameStats;
  categoryStats: CategoryStats;
  categories: string[];
  pets: Pet[];
  achievements: Achievement[];
  userProgress: UserProgress;
  addWord: (word: Omit<Word, 'id' | 'isCustom'>) => void;
  addWords: (words: Omit<Word, 'id' | 'isCustom'>[]) => void;
  deleteWord: (id: string) => void;
  updateSettings: (settings: GameSettings) => void;
  getWordsByCategory: (category: Category) => Word[];
  updateMatchingStats: (time: number) => void;
  updateSpellingStats: (totalWords: number, correctWords: number) => void;
  updateQuizStats: (score: number, correctCount: number, totalCount: number) => void;
  updateCategoryStats: (category: string, correct: boolean) => void;
  addCategory: (category: string) => void;
  feedPet: (petId: string, experience: number) => void;
  checkAchievements: () => void;
}

const VocabularyContext = createContext<VocabularyContextType | undefined>(undefined);

export const VocabularyProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [vocabulary, setVocabulary] = useState<Word[]>([]);
  const [settings, setSettings] = useState<GameSettings>({
    difficulty: 'medium',
    timeLimit: 15,
    soundEnabled: true,
  });
  const [gameStats, setGameStats] = useState<GameStats>({
    matching: {
      totalGames: 0,
      totalTime: 0,
      averageTime: 0,
      bestTime: 0,
    },
    spelling: {
      totalGames: 0,
      totalWords: 0,
      correctWords: 0,
      accuracy: 0,
    },
    quiz: {
      totalGames: 0,
      totalScore: 0,
      averageScore: 0,
      bestScore: 0,
      accuracy: 0,
    },
  });
  const [categoryStats, setCategoryStats] = useState<CategoryStats>({});
  const [categories, setCategories] = useState<string[]>([...defaultCategories]);
  
  // 宠物和成就系统状态
  const [pets, setPets] = useState<Pet[]>([
    {
      id: 'cat',
      name: '小猫咪',
      level: 1,
      experience: 0,
      maxExperience: 100,
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/314a1256-6d50-4ce0-a562-a56f7c785073.jpg',
      isUnlocked: true,
      description: '可爱的小猫咪，陪伴你学习的第一个伙伴',
    },
    {
      id: 'dog',
      name: '小狗狗',
      level: 1,
      experience: 0,
      maxExperience: 100,
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/3c1da528-1936-443b-ba00-a398bd2fec8a.jpg',
      isUnlocked: false,
      description: '忠诚的小狗狗，学习50个单词后解锁',
    },
    {
      id: 'rabbit',
      name: '小兔子',
      level: 1,
      experience: 0,
      maxExperience: 100,
      image: 'https://miaoda-site-img.cdn.bcebos.com/images/34057004-2309-4d61-be27-801ed544ab21.jpg',
      isUnlocked: false,
      description: '活泼的小兔子，学习100个单词后解锁',
    },
  ]);

  const [achievements, setAchievements] = useState<Achievement[]>([
    {
      id: 'first_word',
      title: '初学者',
      description: '学习第一个单词',
      icon: '📚',
      isUnlocked: false,
      progress: 0,
      maxProgress: 1,
      category: 'words',
    },
    {
      id: 'words_10',
      title: '词汇新手',
      description: '学习10个单词',
      icon: '📖',
      isUnlocked: false,
      progress: 0,
      maxProgress: 10,
      category: 'words',
    },
    {
      id: 'words_50',
      title: '词汇达人',
      description: '学习50个单词',
      icon: '📕',
      isUnlocked: false,
      progress: 0,
      maxProgress: 50,
      category: 'words',
    },
    {
      id: 'words_100',
      title: '词汇大师',
      description: '学习100个单词',
      icon: '📗',
      isUnlocked: false,
      progress: 0,
      maxProgress: 100,
      category: 'words',
    },
    {
      id: 'first_game',
      title: '游戏初体验',
      description: '完成第一个游戏',
      icon: '🎮',
      isUnlocked: false,
      progress: 0,
      maxProgress: 1,
      category: 'games',
    },
    {
      id: 'games_10',
      title: '游戏爱好者',
      description: '完成10个游戏',
      icon: '🎯',
      isUnlocked: false,
      progress: 0,
      maxProgress: 10,
      category: 'games',
    },
    {
      id: 'perfect_quiz',
      title: '完美答题',
      description: '在快速测验中获得满分',
      icon: '⭐',
      isUnlocked: false,
      progress: 0,
      maxProgress: 1,
      category: 'special',
    },
    {
      id: 'streak_7',
      title: '坚持不懈',
      description: '连续学习7天',
      icon: '🔥',
      isUnlocked: false,
      progress: 0,
      maxProgress: 7,
      category: 'streak',
    },
  ]);

  const [userProgress, setUserProgress] = useState<UserProgress>({
    totalWordsLearned: 0,
    totalExperience: 0,
    availableExperience: 0,
    currentStreak: 0,
    longestStreak: 0,
    lastStudyDate: '',
  });

  useEffect(() => {
    setVocabulary(loadVocabulary());
    setSettings(loadSettings());
    setGameStats(loadGameStats());
    setCategoryStats(loadCategoryStats());
    
    // 从localStorage加载自定义类别
    const savedCategories = localStorage.getItem('customCategories');
    if (savedCategories) {
      const customCategories = JSON.parse(savedCategories);
      setCategories([...defaultCategories, ...customCategories]);
    }

    // 加载宠物、成就和用户进度数据
    const savedPets = loadPets();
    if (savedPets) {
      setPets(savedPets);
    }

    const savedAchievements = loadAchievements();
    if (savedAchievements) {
      setAchievements(savedAchievements);
    }

    const savedProgress = loadUserProgress();
    if (savedProgress) {
      setUserProgress(savedProgress);
    }
  }, []);

  const addWord = (word: Omit<Word, 'id' | 'isCustom'>) => {
    const newWord: Word = {
      ...word,
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      isCustom: true,
    };
    const updatedVocabulary = [...vocabulary, newWord];
    setVocabulary(updatedVocabulary);
    saveVocabulary(updatedVocabulary);
  };

  const addWords = (words: Omit<Word, 'id' | 'isCustom'>[]) => {
    const newWords: Word[] = words.map((word, index) => ({
      ...word,
      id: `${Date.now()}-${index}-${Math.random().toString(36).substr(2, 9)}`,
      isCustom: true,
    }));
    const updatedVocabulary = [...vocabulary, ...newWords];
    setVocabulary(updatedVocabulary);
    saveVocabulary(updatedVocabulary);
  };

  const deleteWord = (id: string) => {
    const updatedVocabulary = vocabulary.filter(w => w.id !== id);
    setVocabulary(updatedVocabulary);
    saveVocabulary(updatedVocabulary);
  };

  const updateSettings = (newSettings: GameSettings) => {
    setSettings(newSettings);
    saveSettings(newSettings);
  };

  const getWordsByCategory = (category: Category): Word[] => {
    if (category === '全部类别') {
      return vocabulary;
    }
    return vocabulary.filter(w => w.category === category);
  };

  const updateMatchingStats = (time: number) => {
    const newStats = { ...gameStats };
    newStats.matching.totalGames += 1;
    newStats.matching.totalTime += time;
    newStats.matching.averageTime = Math.round(newStats.matching.totalTime / newStats.matching.totalGames);
    if (newStats.matching.bestTime === 0 || time < newStats.matching.bestTime) {
      newStats.matching.bestTime = time;
    }
    setGameStats(newStats);
    saveGameStats(newStats);

    // 增加经验值和学习单词数
    const wordsLearned = 7; // 配对游戏有7对单词
    const expGained = 10;
    const updatedProgress = {
      ...userProgress,
      totalWordsLearned: userProgress.totalWordsLearned + wordsLearned,
      totalExperience: userProgress.totalExperience + expGained,
      availableExperience: userProgress.availableExperience + expGained,
      lastStudyDate: new Date().toISOString().split('T')[0],
    };
    setUserProgress(updatedProgress);
    saveUserProgress(updatedProgress);
    
    // 延迟检查成就，确保状态已更新
    setTimeout(() => checkAchievements(), 100);
  };

  const updateSpellingStats = (totalWords: number, correctWords: number) => {
    const newStats = { ...gameStats };
    newStats.spelling.totalGames += 1;
    newStats.spelling.totalWords += totalWords;
    newStats.spelling.correctWords += correctWords;
    newStats.spelling.accuracy = Math.round((newStats.spelling.correctWords / newStats.spelling.totalWords) * 100);
    setGameStats(newStats);
    saveGameStats(newStats);

    // 增加经验值和学习单词数
    const expGained = correctWords * 2;
    const updatedProgress = {
      ...userProgress,
      totalWordsLearned: userProgress.totalWordsLearned + correctWords,
      totalExperience: userProgress.totalExperience + expGained,
      availableExperience: userProgress.availableExperience + expGained,
      lastStudyDate: new Date().toISOString().split('T')[0],
    };
    setUserProgress(updatedProgress);
    saveUserProgress(updatedProgress);
    
    setTimeout(() => checkAchievements(), 100);
  };

  const updateQuizStats = (score: number, correctCount: number, totalCount: number) => {
    const newStats = { ...gameStats };
    newStats.quiz.totalGames += 1;
    newStats.quiz.totalScore += score;
    newStats.quiz.averageScore = Math.round(newStats.quiz.totalScore / newStats.quiz.totalGames);
    if (score > newStats.quiz.bestScore) {
      newStats.quiz.bestScore = score;
    }
    const totalCorrect = (newStats.quiz.accuracy * (newStats.quiz.totalGames - 1) * totalCount + correctCount * 100) / (newStats.quiz.totalGames * totalCount);
    newStats.quiz.accuracy = Math.round(totalCorrect);
    setGameStats(newStats);
    saveGameStats(newStats);

    // 增加经验值和学习单词数
    const expGained = Math.floor(score / 10);
    const updatedProgress = {
      ...userProgress,
      totalWordsLearned: userProgress.totalWordsLearned + correctCount,
      totalExperience: userProgress.totalExperience + expGained,
      availableExperience: userProgress.availableExperience + expGained,
      lastStudyDate: new Date().toISOString().split('T')[0],
    };
    setUserProgress(updatedProgress);
    saveUserProgress(updatedProgress);
    
    setTimeout(() => checkAchievements(), 100);
  };

  const updateCategoryStats = (category: string, correct: boolean) => {
    const newStats = { ...categoryStats };
    if (!newStats[category]) {
      newStats[category] = {
        attempted: 0,
        correct: 0,
        accuracy: 0,
      };
    }
    newStats[category].attempted += 1;
    if (correct) {
      newStats[category].correct += 1;
    }
    newStats[category].accuracy = Math.round((newStats[category].correct / newStats[category].attempted) * 100);
    setCategoryStats(newStats);
    saveCategoryStats(newStats);
  };

  const addCategory = (category: string) => {
    if (!categories.includes(category) && category !== '全部类别') {
      const newCategories = [...categories, category];
      setCategories(newCategories);
      
      // 保存自定义类别到localStorage
      const defaultCats = [...defaultCategories] as string[];
      const customCategories = newCategories.filter(cat => !defaultCats.includes(cat));
      localStorage.setItem('customCategories', JSON.stringify(customCategories));
    }
  };

  const feedPet = (petId: string, experience: number) => {
    if (userProgress.availableExperience < experience) {
      return; // 经验值不足
    }

    const updatedPets = pets.map(pet => {
      if (pet.id === petId && pet.isUnlocked) {
        const newExperience = pet.experience + experience;
        const newLevel = Math.floor(newExperience / pet.maxExperience) + 1;
        return {
          ...pet,
          experience: newExperience % pet.maxExperience,
          level: newLevel,
          maxExperience: pet.maxExperience + (newLevel - pet.level) * 20,
        };
      }
      return pet;
    });

    const updatedProgress = {
      ...userProgress,
      availableExperience: userProgress.availableExperience - experience,
    };

    setPets(updatedPets);
    setUserProgress(updatedProgress);
    savePets(updatedPets);
    saveUserProgress(updatedProgress);
  };

  const checkAchievements = () => {
    const totalGames = gameStats.matching.totalGames + gameStats.spelling.totalGames + gameStats.quiz.totalGames;
    
    const updatedAchievements = achievements.map(achievement => {
      let progress = achievement.progress;
      
      switch (achievement.id) {
        case 'first_word':
          progress = Math.min(userProgress.totalWordsLearned, 1);
          break;
        case 'words_10':
          progress = Math.min(userProgress.totalWordsLearned, 10);
          break;
        case 'words_50':
          progress = Math.min(userProgress.totalWordsLearned, 50);
          break;
        case 'words_100':
          progress = Math.min(userProgress.totalWordsLearned, 100);
          break;
        case 'first_game':
          progress = Math.min(totalGames, 1);
          break;
        case 'games_10':
          progress = Math.min(totalGames, 10);
          break;
        case 'perfect_quiz':
          if (gameStats.quiz.bestScore >= 1000) {
            progress = 1;
          }
          break;
        case 'streak_7':
          progress = Math.min(userProgress.currentStreak, 7);
          break;
      }

      const isUnlocked = progress >= achievement.maxProgress;
      return { ...achievement, progress, isUnlocked };
    });

    setAchievements(updatedAchievements);
    saveAchievements(updatedAchievements);

    // 检查宠物解锁条件
    const updatedPets = pets.map(pet => {
      if (pet.id === 'dog' && userProgress.totalWordsLearned >= 50) {
        return { ...pet, isUnlocked: true };
      }
      if (pet.id === 'rabbit' && userProgress.totalWordsLearned >= 100) {
        return { ...pet, isUnlocked: true };
      }
      return pet;
    });

    setPets(updatedPets);
    savePets(updatedPets);
  };

  return (
    <VocabularyContext.Provider
      value={{
        vocabulary,
        settings,
        gameStats,
        categoryStats,
        categories,
        pets,
        achievements,
        userProgress,
        addWord,
        addWords,
        deleteWord,
        updateSettings,
        getWordsByCategory,
        updateMatchingStats,
        updateSpellingStats,
        updateQuizStats,
        updateCategoryStats,
        addCategory,
        feedPet,
        checkAchievements,
      }}
    >
      {children}
    </VocabularyContext.Provider>
  );
};

export const useVocabulary = () => {
  const context = useContext(VocabularyContext);
  if (!context) {
    throw new Error('useVocabulary must be used within VocabularyProvider');
  }
  return context;
};
